<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '230px'">
      <!-- Logo 区域 -->
      <div class="logo-container" :class="{ collapsed: isCollapse }">
        <img src="/vite.svg" alt="Logo" class="logo" />
        <h1 class="title" v-show="!isCollapse">图书管理系统</h1>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <el-menu-item
          index="/layout/dashboard"
          @click="handleSelect('/layout/dashboard')"
        >
          <el-icon><DataLine /></el-icon>
          <span>仪表板</span>
        </el-menu-item>
        <el-menu-item
          index="/layout/book"
          @click="handleSelect('/layout/book')"
        >
          <el-icon><Document /></el-icon>
          <span>图书管理</span>
        </el-menu-item>
        <el-menu-item
          index="/layout/reader"
          @click="handleSelect('/layout/reader')"
        >
          <el-icon><Reading /></el-icon>
          <span>读者管理</span>
        </el-menu-item>
        <el-menu-item
          index="/layout/user"
          @click="handleSelect('/layout/user')"
        >
          <el-icon><User /></el-icon>
          <span>用户管理</span>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <el-container class="right-container">
      <!-- 头部 -->
      <el-header>
        <div class="header-left">
          <el-icon class="fold-btn" @click="toggleCollapse">
            <Expand v-if="isCollapse" />
            <Fold v-else />
          </el-icon>
        </div>
        <div class="header-right">
          <!-- 添加消息通知 -->
          <el-popover
            placement="bottom"
            :width="300"
            trigger="click"
            popper-class="message-popover"
          >
            <template #reference>
              <div class="message-badge">
                <el-badge :value="unreadCount" :max="99" class="notice-badge">
                  <el-icon class="notice-icon"><Bell /></el-icon>
                </el-badge>
              </div>
            </template>

            <template #default>
              <div class="message-header">
                <span>消息通知</span>
                <el-link type="primary" :underline="false" @click="readAll"
                  >全部已读</el-link
                >
              </div>
              <el-scrollbar max-height="300px">
                <div v-if="messages.length" class="message-list">
                  <div
                    v-for="msg in messages"
                    :key="msg.id"
                    class="message-item"
                    :class="{ unread: !msg.isRead }"
                    @click="handleRead(msg)"
                  >
                    <el-icon :class="['msg-icon', msg.type]">
                      <component :is="getIcon(msg.type)" />
                    </el-icon>
                    <div class="msg-content">
                      <div class="msg-title">{{ msg.title }}</div>
                      <div class="msg-time">{{ msg.time }}</div>
                    </div>
                  </div>
                </div>
                <el-empty v-else description="暂无消息" />
              </el-scrollbar>
            </template>
          </el-popover>

          <!-- 原有的用户下拉菜单 -->
          <el-dropdown>
            <span class="user-info">
              <el-avatar :size="32" :src="userInfo.imgPath" class="user-avatar">
                <img :src="userInfo.imgPath" />
              </el-avatar>
              <span class="username">{{ userInfo.nickname }}</span>
              <el-icon><CaretBottom /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleSelect('/layout/profile')">
                  <el-icon><User /></el-icon>个人信息
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 导航标签栏 -->
      <div class="nav-tags-container">
        <el-scrollbar class="tags-scrollbar" wrap-class="scrollbar-wrapper">
          <div class="nav-tags">
            <el-tag
              v-for="tag in visitedViews"
              :key="tag.path"
              :type="isActive(tag) ? '' : 'info'"
              closable
              :disable-transitions="false"
              @click="handleTagClick(tag)"
              @close="handleCloseTag(tag)"
              class="nav-tag"
              :class="{ active: isActive(tag) }"
            >
              {{ tag.title }}
            </el-tag>
          </div>
        </el-scrollbar>
        <div class="tags-action">
          <el-dropdown trigger="hover">
            <el-button size="small" type="primary" plain>
              标签操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="closeOtherTags"
                  >关闭其他</el-dropdown-item
                >
                <el-dropdown-item @click="closeAllTags"
                  >关闭所有</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区 -->
      <el-main>
        <router-view v-slot="{ Component }">
          <transition name="fade" mode="out-in">
            <component :is="Component" />
          </transition>
        </router-view>
        <!-- 底部关于信息 -->
        <div class="main-footer">
          <div class="footer-content">
            <span class="copyright">© 2024 图书管理系统</span>
            <span class="divider">|</span>
            <span class="version">Version 1.0.0</span>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  Document,
  Fold,
  Expand,
  CaretBottom,
  User,
  Collection,
  SwitchButton,
  Reading,
  ArrowDown,
  DataLine,
  Bell,
  Warning,
  InfoFilled,
  CircleCheckFilled,
} from "@element-plus/icons-vue";
import { removeToken } from "../utils/cookie";
import { getUserInfo } from "../apis/user";

const route = useRoute();
const router = useRouter();

// 侧边栏折叠状态
const isCollapse = ref(false);

const userInfo = ref({
  username: "",
  nickname: "",
  email: "",
  imgPath:
    "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
});

getUserInfo().then((res) => {
  userInfo.value = res.data;
});

// 切换折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value;
};

// 当前激活的菜单
const activeMenu = computed(() => route.path);

// 菜单选择处理
const handleSelect = (path) => {
  router.push(path);
};

// 退出登录
const handleLogout = () => {
  removeToken();
  router.push("/login");
};

// 访问过的页面标签
const visitedViews = ref([]);

// 判断标签是否激活
const isActive = (tag) => {
  return tag.path === route.path;
};

// 点击标签
const handleTagClick = (tag) => {
  router.push(tag.path);
};

// 关闭标签
const handleCloseTag = (tag) => {
  const index = visitedViews.value.indexOf(tag);
  if (index > -1) {
    visitedViews.value.splice(index, 1);
  }
  // 如果关闭的是当前页，则跳转到最后一个标签
  if (isActive(tag) && visitedViews.value.length) {
    const latestView = visitedViews.value[visitedViews.value.length - 1];
    router.push(latestView.path);
  }
};

// 关闭其他标签
const closeOtherTags = () => {
  const currentTag = visitedViews.value.find((tag) => isActive(tag));
  if (currentTag) {
    visitedViews.value = [currentTag];
  }
};

// 关闭所有标签
const closeAllTags = () => {
  visitedViews.value = [];
  router.push("/layout/book");
};

// 监听路由变化，添加新的标签
watch(
  () => route.path,
  (newPath) => {
    const title = route.meta.title || route.name;
    if (!visitedViews.value.some((v) => v.path === newPath)) {
      visitedViews.value.push({
        path: newPath,
        title: title,
      });
    }
  },
  { immediate: true }
);

// 模拟消息数据
const messages = ref([
  {
    id: 1,
    type: "info",
    title: "系统将于今晚22:00进行维护更新",
    time: "10分钟前",
    isRead: false,
  },
  {
    id: 2,
    type: "warning",
    title: "有3本图书即将到期",
    time: "30分钟前",
    isRead: false,
  },
  {
    id: 3,
    type: "success",
    title: "新增图书入库完成",
    time: "1小时前",
    isRead: true,
  },
]);

// 未读消息数量
const unreadCount = computed(
  () => messages.value.filter((msg) => !msg.isRead).length
);

// 获取消息图标
const getIcon = (type) => {
  const icons = {
    info: InfoFilled,
    warning: Warning,
    success: CircleCheckFilled,
  };
  return icons[type];
};

// 标记消息已读
const handleRead = (msg) => {
  msg.isRead = true;
};

// 全部标记已读
const readAll = () => {
  messages.value.forEach((msg) => (msg.isRead = true));
};
</script>

<style scoped lang="scss">
/* 布局容器 */
.layout-container {
  height: 100vh;
}

/* 侧边栏 */
.el-aside {
  background-color: #304156;
  transition: width 0.3s;
}

.logo-container {
  height: 55px;
  padding: 0 20px;
  display: flex;
  align-items: center;
  background-color: #2b2f3a;
  overflow: hidden;
  transition: all 0.3s;
}

.logo-container.collapsed {
  padding: 0 20px;
  justify-content: center;
}

.logo-container.collapsed .logo {
  margin-right: 0;
}

.logo {
  width: 24px;
  height: 24px;
  margin-right: 12px;
}

.title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  white-space: nowrap;
  margin: 0;
}

/* 菜单 */
.el-menu {
  border-right: none;
}

.el-menu-vertical:not(.el-menu--collapse) {
  width: 230px;
}

/* 头部 */
.el-header {
  background-color: #fff;
  display: flex;
  height: 55px;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-left {
  display: flex;
  align-items: center;
}

.fold-btn {
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #666;
  padding: 0 8px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f6f6f6;
}

.user-avatar {
  margin-right: 8px;
  border: 2px solid #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.username {
  font-size: 14px;
  margin-right: 4px;
}

.el-dropdown-menu__item .el-icon {
  margin-right: 8px;
}

/* 右侧容器 */
.right-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

/* 导航标签栏样式优化 */
.nav-tags-container {
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  border-bottom: 1px solid #d8dce5;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.12), 0 0 3px 0 rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  padding: 0 10px;
  height: 40px;
  z-index: 10;
}

.tags-scrollbar {
  flex: 1;
  width: 0;
}

:deep(.el-scrollbar__wrap) {
  height: 40px;
}

:deep(.el-scrollbar__view) {
  height: 100%;
  display: flex;
  align-items: center;
}

.nav-tags {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 10px;
}

.nav-tag {
  margin-right: 4px;
  cursor: pointer;
  height: 28px;
  line-height: 26px;
  border-radius: 2px;
  border: 1px solid #e8eaec;
  background: #fff;
  padding: 0 8px;
  font-size: 12px;
  color: #666;
  transition: all 0.2s ease-in-out;
  display: inline-flex;
  align-items: center;
}

.nav-tag:not(.active):hover {
  color: #409eff;
  border-color: #409eff;
}

.nav-tag.active {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}

.tags-action {
  margin-left: 8px;
  padding-left: 8px;
  border-left: 1px solid #f0f0f0;
}

/* 主内容区域优化 */
.el-main {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  background-color: #f0f2f5;
  position: relative;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 95px); /* 减去头部和标签栏的高度 */
}

/* 页面切换动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.15s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 底部样式优化 */
.main-footer {
  margin-top: auto;
  padding-top: 12px;
  text-align: center;
  color: #909399;
  font-size: 12px;
  border-top: 1px solid #e8e8e8;
  width: 100%;
}

.footer-content {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
}

.copyright,
.version {
  color: #909399;
}

.divider {
  color: #dcdfe6;
}

/* 滚动条样式优化 */
:deep(.el-scrollbar__wrap) {
  height: 100%;
}

:deep(.el-scrollbar__bar.is-horizontal) {
  height: 4px;
}

:deep(.el-scrollbar__thumb) {
  background-color: rgba(144, 147, 153, 0.3);
}

/* 消息通知样式优化 */
.message-badge {
  margin-right: 5px;
  margin-top: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.3s;

  &:hover {
    background-color: #f6f6f6;
  }
}

.notice-icon {
  font-size: 20px;
  color: #606266;
}

.notice-badge :deep(.el-badge__content) {
  background-color: #f56c6c;
}

.message-header {
  padding: 12px 16px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #303133;
}

.message-list {
  .message-item {
    padding: 12px 16px;
    display: flex;
    align-items: flex-start;
    cursor: pointer;
    transition: background-color 0.3s;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .msg-icon {
      font-size: 16px;
      margin-right: 12px;
      margin-top: 2px;
    }

    .msg-content {
      flex: 1;
      min-width: 0;
    }

    &:hover {
      background-color: #f5f7fa;
    }

    &.unread {
      background-color: #f0f9ff;
    }
  }
}

:deep(.el-scrollbar__view) {
  padding: 0;
}

:deep(.el-empty) {
  padding: 20px 0;
}
</style>
